package abstract01.factory;

/**
 * @author feng
 * @Date 2021/12/9 7:53
 * 单例模式
 * 构造方法私有化
 * 静态属性指向实例
 * public static的getlnstance方法，返回第二步的静态属性
 * 饿汉模式
 */
public class SingleTest {
    public static void main(String[] args) {
        Person person = Person.getInstance01();
        Person person1 = Person.getInstance01();
        System.out.println("饿汉模式" + (person == person1));
        Cat instance02 = Cat.getInstance02();
        Cat cat = Cat.getInstance02();
        System.out.println("懒汉模式" + (cat == instance02));
    }

}

//饿汉模式
class Person {

    private Person() {
        System.out.println("私有的构造方法");
    }

    private static Person instance = new Person();

    public static Person getInstance01() {
        return instance;
    }


}

//懒汉面试(线程安全考量)
class Cat {
    private Cat() {
        System.out.println("私有的构造方法");
    }

    private static Object obj = new Object();
    private static Cat instance = null;

    public static Cat getInstance02() {
        if (null == instance) {
            synchronized (obj) {
                if (null == instance)
                    instance = new Cat();
            }
        }
        return instance;
    }

}
